import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/components/diolog/dialog.dart';
import 'package:pornhub_app/components/image_view.dart';
import 'package:pornhub_app/generate/app_image_path.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:pornhub_app/views/community/post_publish/publish_rules.dart';
import 'post_publish_page_controller.dart';

class PostPublishPage extends GetView<PostPublishPageController> {
  const PostPublishPage({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(PostPublishPageController());

    return KeyboardDismissOnTap(
      child: Scaffold(
        backgroundColor: Colors.black,
        appBar: _buildAppBar(),
        body: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildContentInput(),
                        const SizedBox(height: 20),
                        _buildTypeSelectionHeader(),
                        const SizedBox(height: 10),
                        _buildTypeSelection(),
                        const SizedBox(height: 26),
                        _buildImageSelectionHeader(),
                        const SizedBox(height: 10),
                        _buildImageGrid(),
                      ],
                    ),
                  ),
                ),
              ),
              _buildBottomPublishArea(),
              const SizedBox(height: 10),
            ],
          ),
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.black,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back, color: Colors.white),
        onPressed: () => Get.back(),
      ),
      title: const Text(
        "发布帖子",
        style: TextStyle(
          color: Colors.white,
          fontWeight: FontWeight.w500,
          fontSize: 18.0,
        ),
      ),
    );
  }

  Widget _buildContentInput() {
    return TextField(
      controller: controller.textController,
      style: const TextStyle(color: Colors.white),
      maxLines: 8,
      cursorColor: Colors.white,
      decoration: InputDecoration(
        hintText: '请输入帖子内容...',
        hintStyle: TextStyle(
          color: Colors.white.withOpacity(0.6),
          fontWeight: FontWeight.w600,
          fontSize: 16.0,
        ),
        border: InputBorder.none,
      ),
    );
  }

  Widget _buildTypeSelectionHeader() {
    return Row(
      children: [
        const Text(
          "选择发布类型",
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w600,
            fontSize: 16.0,
          ),
        ),
        Opacity(
          opacity: 0.6,
          child: Padding(
            padding: const EdgeInsets.only(top: 2),
            child: Text(
              " (必填)",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w600,
                fontSize: 12.0,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTypeSelection() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Obx(() {
        return Row(
          children: controller.publishTagsList.map((tag) {
            return Padding(
              padding: const EdgeInsets.only(right: 10),
              child: _buildTypeButton(tag.name),
            );
          }).toList(),
        );
      }),
    );
  }

  Widget _buildTypeButton(String type) {
    return Obx(() {
      final isSelected = controller.isTypeSelected(type);
      return GestureDetector(
        onTap: () => controller.toggleType(type),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          decoration: BoxDecoration(
            color: isSelected ? const Color(0xffff9000) : const Color(0xff272727),
            borderRadius: BorderRadius.circular(20),
            // 可以添加边框来更明显地显示选中状态
            border: isSelected
                ? Border.all(color: const Color(0xffff9000), width: 2)
                : null,
          ),
          child: Text(
            type,
            style: TextStyle(
              color: isSelected ? Colors.black : Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      );
    });
  }


  Widget _buildImageSelectionHeader() {
    return Row(
      children: [
        const Text(
          "选择图片",
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w600,
            fontSize: 16.0,
          ),
        ),
        Opacity(
          opacity: 0.6,
          child: Padding(
            padding: const EdgeInsets.only(top: 3),
            child: Text(
              "  (最多选择9张图片)",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w600,
                fontSize: 12.0,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildImageGrid() {
    return Obx(
          () => Container(
        height: ((controller.images.length + 1) / 3).ceil() * 123.0,
        child: GridView.builder(
          physics: const NeverScrollableScrollPhysics(),
          padding: const EdgeInsets.all(8),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 8,
            crossAxisSpacing: 8,
            childAspectRatio: 1,
          ),
          itemCount: controller.images.length + 1,
          itemBuilder: (context, index) {
            if (index == 0) {
              return _buildAddImageButton();
            }
            return _buildImageItem(index - 1);
          },
        ),
      ),
    );
  }

  Widget _buildAddImageButton() {
    return GestureDetector(
      onTap: () => controller.pickImages(),
      child: Container(
        decoration: BoxDecoration(
          color: const Color(0xff272727),
          borderRadius: BorderRadius.circular(8),
        ),
        child: const Center(
          child: Icon(
            Icons.add,
            color: Color(0xffa4a4a4),
            size: 40,
          ),
        ),
      ),
    );
  }

  Widget _buildImageItem(int index) {
    return Stack(
      children: [
        Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(8),
            image: DecorationImage(
              image: FileImage(controller.images[index]),
              fit: BoxFit.cover,
            ),
          ),
        ),
        Positioned(
          right: 0,
          top: 0,
          child: ImageView(
            src: AppImagePath.community_image_close,
            width: 20.w,
            height: 20.w,
          ).onOpaqueTap(() {
            controller.removeImage(index);
          }).onTap(() {
            controller.removeImage(index);
          }),
        ),
      ],
    );
  }

  Widget _buildBottomPublishArea() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: const BoxDecoration(
        color: Colors.black,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _buildAgreementRow(),
          const SizedBox(height: 20),
          _buildPublishButton(),
        ],
      ),
    );
  }

  Widget _buildAgreementRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Obx(() => GestureDetector(
          onTap: controller.toggleAgreement,
          child: Icon(
            controller.isAgreedToRules.value
                ? Icons.check_circle
                : Icons.radio_button_unchecked,
            color: controller.isAgreedToRules.value
                ? const Color(0xffff9000)
                : Colors.grey,
            size: 20,
          ),
        )),
        const SizedBox(width: 8),
        const Text(
          "请阅读并遵守",
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w400,
            fontSize: 12.0,
          ),
        ),
        GestureDetector(
          onTap: () {
            Get.to(PublishRulesPage(), opaque: false);
          },
          child: const Padding(
            padding: EdgeInsets.only(left: 3),
            child: Text(
              "《发布规则》",
              style: TextStyle(
                color: Color(0xffff9000),
                fontWeight: FontWeight.w400,
                fontSize: 12.0,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildPublishButton() {
    return Obx(() => GestureDetector(
      onTap: () {
        if (!controller.isAgreedToRules.value) {
          showToast("请先阅读并同意发布规则");
          return;
        }
        if (controller.isLoading.value) return;

        controller.publishRelease();
      },
      child: Container(
        width: ScreenUtil().screenWidth,
        height: 42,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(21)),
          color: controller.isLoading.value
              ? Colors.grey
              : const Color(0xffff9000),
        ),
        child: controller.isLoading.value
            ? const SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
          ),
        )
            : const Text(
          "发布",
          style: TextStyle(
            color: Color(0xff000000),
            fontWeight: FontWeight.w600,
            fontSize: 16.0,
          ),
        ),
      ),
    ));
  }
}
